/*
 * NewClass.java
 *
 * Created on April 24, 2009, 4:12 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package org.naga.bulksender.callback;

import org.naga.bulksender.dal.BulkMessageDaoIfc;
import org.naga.bulksender.data.BulkMessage;
import org.smslib.IOutboundMessageNotification;
import org.smslib.OutboundMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.naga.bulksender.data.SMSBulkContext;

/**
 * Outbound Callback Implementation
 * @author Naga Services
 */
public class OutboundMessageCallback implements IOutboundMessageNotification {

    private Log log = LogFactory.getLog(OutboundMessageCallback.class);
    private BulkMessageDaoIfc msgDao = null;
    private SMSBulkContext bulkCtx = null;

    /** Creates a new instance of NewClass */
    public OutboundMessageCallback() {
    }

    public void setMessageDao(BulkMessageDaoIfc dao) {
        msgDao = dao;
    }

    public void setBulkContext(SMSBulkContext ctx) {
        bulkCtx = ctx;
    }

    public void process(String gatewayId, OutboundMessage outboundMessage) {
        log.debug("Process Callback Method ");
        int newTotal = 0;
        Integer msgId = Integer.parseInt(outboundMessage.getId());
        BulkMessage bulkMsg = this.bulkCtx.getMessage(msgId);

        msgDao.logMsgSent(msgId, outboundMessage.getRecipient());
        if (bulkMsg != null) {
            newTotal = bulkMsg.decreaseSmsCounter();
        }
        if (newTotal == 0) {
            log.debug("Change the Status to Sent :: MsgId=>" + msgId);
            msgDao.changeMessageStatus(msgId, "Sent");
            bulkCtx.removeMessage(msgId);
            //TODO Inject the Service Provide and based in the receipent we can remove the group created
        } else if (newTotal > 0) {
            log.debug("Change the Status to Sending :: MsgId=>" + bulkMsg.getBulkSmsId());
            msgDao.changeMessageStatus(bulkMsg.getBulkSmsId(), "Sending");
            // Defin the Status of the Messages in Member Contants
        }

    }
}
